package es.truscoandrisco.discotecasmadrid;

import java.util.List;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;



public class mapas extends MapActivity{
	
	private MapView mapview;
	private MapController mapControl;
	//private LocationHandler mLocationHandler;
	private List<Overlay> mapOverlays;
	private int latDisco;
	private int lonDisco;
	private String nombre;
	public GeoPoint discoPoint;
	private GeoPoint currentPoint = null;
	private boolean tenemosIntent = true;
	private LocationManager lm;
	private LocationListener ll;
	private ProgressDialog pd;
	private Location location;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		super.onCreate(savedInstanceState);
        setContentView(R.layout.mapview);
        
        //mLocationHandler = new LocationHandler((LocationManager)getSystemService(Context.LOCATION_SERVICE));
        
        mapview = (MapView) findViewById(R.id.myMap);
        mapview.setBuiltInZoomControls(true);
        mapview.setClickable(true);
  
        mapControl = mapview.getController();
        
       try {
			latDisco = getIntent().getIntExtra("LATITUD", 0);
			lonDisco = getIntent().getIntExtra("LONGITUD", 0);
			if ((latDisco == 0) && (lonDisco == 0))
				tenemosIntent = false;
			discoPoint = new GeoPoint(latDisco, lonDisco);
			nombre = getIntent().getStringExtra("NOMBRE");
			//pointsToDraw.add(1, discoPoint); //set(1, discoPoint);
        } catch (Exception e) {
        	tenemosIntent = false;
        }
        
        fillMap();
        
	}
	
	public void posicionar(){
        if (location != null) {
        	currentPoint = new GeoPoint((int)(location.getLatitude() * 1000000),
        								(int)(location.getLongitude() * 1000000));
        } else {
        	currentPoint = null;
        	Toast.makeText(this.getApplicationContext(), "No se ha podido ubicar su posición GPS", Toast.LENGTH_LONG).show();
        }
       
        
        if ((currentPoint != null)&&(tenemosIntent))
        	mapControl.zoomToSpan((Math.abs(discoPoint.getLatitudeE6()-currentPoint.getLatitudeE6())*2), 
        	          (Math.abs(discoPoint.getLongitudeE6()-currentPoint.getLongitudeE6()))*2);
        else
            mapControl.zoomToSpan(15000, 15000);

        if (currentPoint != null)
        	mapControl.setCenter(currentPoint);
        else if (tenemosIntent) {
        	GeoPoint discoPoint = new GeoPoint(latDisco, lonDisco);
        	mapControl.setCenter(discoPoint);
        } else {
            GeoPoint basicPoint = new GeoPoint(3,3);
        	mapControl.setCenter(basicPoint);
        }
        
        mapOverlays = mapview.getOverlays();

        if (currentPoint != null) {
        	Drawable drawable = this.getResources().getDrawable(R.drawable.usuario);
        	discoOverlay mDiscoOverlay = new discoOverlay(drawable);
        	OverlayItem overlayitem = new OverlayItem(currentPoint, "Qui estoy", "Me voy de fiesta");
    		mDiscoOverlay.addOverlay(overlayitem);
    		mapOverlays.add(mDiscoOverlay);
        }
        
        if (tenemosIntent) {
        	Drawable drawable = this.getResources().getDrawable(R.drawable.discoteca);
        	discoOverlay mDiscoOverlay = new discoOverlay(drawable);
        	OverlayItem overlayitem = new OverlayItem(discoPoint, nombre, "Vamos allá!");
    		mDiscoOverlay.addOverlay(overlayitem);
    		mapOverlays.add(mDiscoOverlay);
        }
	}
	
	
	public void fillMap () {
		
		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		if (! lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Active el GPS si desea ubicar su posición en el mapa")
			       .setCancelable(false)
			       .setPositiveButton("Activar", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   Intent settingsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);        	   
			        	   startActivity(settingsIntent);
			           }
			       })
			       .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			                posicionar();
			           }
			       }).show();
		}else{
		    pd = new ProgressDialog(this);
		    pd.setTitle("Detectando posición del usuario vía GPS...");
		    pd.setMessage("Si únicamente desea ver la ubicación de la discoteca, pulse cancelar...");
		    pd.setButton("Cancelar", new DialogInterface.OnClickListener(){
		        public void onClick(DialogInterface dialog, int which){
		        	location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		        	lm.removeUpdates(ll);
		        	if (location != null){
		        		Toast.makeText(getBaseContext(), "Ubicado con la última posición conocida", Toast.LENGTH_SHORT).show();
						posicionar();
		        	}else{
						posicionar();
		        	}
		        }
		    });
		    
		    pd.show();

			lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);		 
			ll = new MyLocationListener();	 
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
        
		}
	}

	
//////////////////////////////////////////////////////////////////////////////////////////////////////
	
    private class MyLocationListener implements LocationListener{

		public void onLocationChanged(Location loc) {
			// TODO Auto-generated method stub

			if (loc != null) {
				pd.dismiss();
				lm.removeUpdates(ll);
				location = loc;
				Toast.makeText(getBaseContext(),
			    "Location changed : Lat: " + location.getLatitude() +
				" Lng: " + location.getLongitude(),
				Toast.LENGTH_SHORT).show();
				posicionar();
			}	
		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub		
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}	
    }
	
///////////////////////////////////////////////////////////////////////////////////////////////////////	
	
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	/*
	private void situaUsuario(GeoPoint posUsuario) {
		
		Drawable drawable = this.getResources().getDrawable(R.drawable.usuario);
    	discoOverlay discooverlay = new discoOverlay(drawable);
    	OverlayItem overlayitem = new OverlayItem(posUsuario, "Hola, Mundo!", "I'm in Mexico City!");
    	discooverlay.addOverlay(overlayitem);
    	mapOverlays.add(discooverlay);

	}
	
	private void situaDiscoteca(GeoPoint posDiscoteca, String discoName){

		Drawable drawable = this.getResources().getDrawable(R.drawable.usuario);
    	discoOverlay discooverlay = new discoOverlay(drawable);
    	OverlayItem overlayitem = new OverlayItem(posDiscoteca, "Hola, Mundo!", discoName);
    	discooverlay.addOverlay(overlayitem);
    	mapOverlays.add(discooverlay);
    	
	}
	*/
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
	        case R.id.Actualizar:
	            fillMap();
	            return true;
	        case R.id.about:
	        	Intent i = new Intent(this, About.class);
	        	startActivity(i);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }

}
